package com.example.managemyself.ui.health;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.managemyself.R;
import com.example.managemyself.data.model.Task;
import com.example.managemyself.util.WhiteNoisePlayer;
import com.example.managemyself.viewmodel.HealthViewModel;
import com.example.managemyself.viewmodel.TaskViewModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.stream.Collectors;

public class HealthFragment extends Fragment {

    private static final String TAG = "HealthFragment";

    private HealthViewModel healthViewModel;
    private TaskViewModel taskViewModel;
    
    // 卡片视图
    private CardView cardHeartRate, cardSteps, cardSleep, cardExercise, cardMeditation;
    
    // 心率监测
    private TextView tvHeartRate;
    
    // 步数统计
    private TextView tvSteps;
    private ProgressBar progressSteps;
    
    // 睡眠分析
    private TextView tvSleepTime;
    
    // 锻炼计时
    private TextView tvExerciseTime;
    private Spinner spinnerExerciseTasks;
    private Button btnStartExercise, btnCompleteExercise;
    private CountDownTimer exerciseTimer;
    private long exerciseStartTime = 0;
    private boolean isExercising = false;
    
    // 冥想功能
    private TextView tvMeditationTime;
    private Spinner spinnerMeditationDuration;
    private Button btnStartMeditation, btnStopMeditation;
    private CountDownTimer meditationTimer;
    private boolean isMeditating = false;
    
    // 数据
    private List<Task> exerciseTasks = new ArrayList<>();
    private Random random = new Random();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        try {
        View view = inflater.inflate(R.layout.fragment_health, container, false);
        initViews(view);
        return view;
        } catch (Exception e) {
            Log.e(TAG, "Error in onCreateView", e);
            Toast.makeText(getContext(), "页面加载失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            return new View(requireContext());
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        try {
        healthViewModel = new ViewModelProvider(this).get(HealthViewModel.class);
            taskViewModel = new ViewModelProvider(requireActivity()).get(TaskViewModel.class);
            
            setupCardListeners();
            setupExerciseFeature();
            setupMeditationFeature();
        setupObservers();
            
            // 初始化模拟数据
            initializeSimulatedData();
        } catch (Exception e) {
            Log.e(TAG, "Error in onViewCreated", e);
            Toast.makeText(getContext(), "功能初始化失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void initViews(View view) {
        try {
            // 卡片视图
            cardHeartRate = view.findViewById(R.id.cardHeartRate);
            cardSteps = view.findViewById(R.id.cardSteps);
            cardSleep = view.findViewById(R.id.cardSleep);
            cardExercise = view.findViewById(R.id.cardExercise);
            cardMeditation = view.findViewById(R.id.cardMeditation);
            
            // 心率监测
            tvHeartRate = view.findViewById(R.id.tvHeartRate);
            
            // 步数统计
            tvSteps = view.findViewById(R.id.tvSteps);
            progressSteps = view.findViewById(R.id.progressSteps);
            
            // 睡眠分析
            tvSleepTime = view.findViewById(R.id.tvSleepTime);
            
            // 锻炼计时
            tvExerciseTime = view.findViewById(R.id.tvExerciseTime);
            spinnerExerciseTasks = view.findViewById(R.id.spinnerExerciseTasks);
            btnStartExercise = view.findViewById(R.id.btnStartExercise);
            btnCompleteExercise = view.findViewById(R.id.btnCompleteExercise);
            
            // 冥想功能
            tvMeditationTime = view.findViewById(R.id.tvMeditationTime);
            spinnerMeditationDuration = view.findViewById(R.id.spinnerMeditationDuration);
            btnStartMeditation = view.findViewById(R.id.btnStartMeditation);
            btnStopMeditation = view.findViewById(R.id.btnStopMeditation);
            
        } catch (Exception e) {
            Log.e(TAG, "Error initializing views", e);
            throw e;
        }
    }
    
    private void setupCardListeners() {
        // 心率监测卡片点击
        if (cardHeartRate != null) {
            cardHeartRate.setOnClickListener(v -> {
                // 模拟心率数据更新
                updateHeartRate();
                Toast.makeText(getContext(), "心率数据已更新", Toast.LENGTH_SHORT).show();
            });
        }
        
        // 步数统计卡片点击
        if (cardSteps != null) {
            cardSteps.setOnClickListener(v -> {
                // 模拟步数增加
                updateSteps();
                Toast.makeText(getContext(), "步数数据已更新", Toast.LENGTH_SHORT).show();
            });
        }
        
        // 睡眠分析卡片点击
        if (cardSleep != null) {
            cardSleep.setOnClickListener(v -> {
                // 模拟睡眠数据更新
                updateSleepData();
                Toast.makeText(getContext(), "睡眠数据已更新", Toast.LENGTH_SHORT).show();
            });
        }
    }
    
    private void setupExerciseFeature() {
        // 设置锻炼任务下拉选择
        setupExerciseTaskSpinner();
        
        // 开始锻炼按钮
        if (btnStartExercise != null) {
            btnStartExercise.setOnClickListener(v -> {
                if (!isExercising) {
                    startExercise();
                } else {
                    pauseExercise();
                }
            });
        }
        
        // 完成锻炼按钮
        if (btnCompleteExercise != null) {
            btnCompleteExercise.setOnClickListener(v -> completeExercise());
        }
    }
    
    private void setupMeditationFeature() {
        // 设置冥想时长选择
        setupMeditationDurationSpinner();
        
        // 开始冥想按钮
        if (btnStartMeditation != null) {
            btnStartMeditation.setOnClickListener(v -> startMeditation());
        }
        
        // 停止冥想按钮
        if (btnStopMeditation != null) {
            btnStopMeditation.setOnClickListener(v -> stopMeditation());
        }
    }

    private void setupObservers() {
        // 观察杂务类型的任务
        if (taskViewModel != null) {
            taskViewModel.getAllTasks().observe(getViewLifecycleOwner(), tasks -> {
                exerciseTasks = tasks.stream()
                        .filter(t -> !t.isCompleted() && ("杂务".equals(t.getType()) || "健康".equals(t.getType())))
                        .collect(Collectors.toList());
                updateExerciseTaskSpinner();
            });
        }
    }
    
    private void initializeSimulatedData() {
        // 初始化心率数据
        updateHeartRate();
        
        // 初始化步数数据
        updateSteps();
        
        // 初始化睡眠数据
        updateSleepData();
    }
    
    private void updateHeartRate() {
        // 模拟心率数据 (60-100 bpm)
        int heartRate = 60 + random.nextInt(41);
        if (tvHeartRate != null) {
            tvHeartRate.setText(heartRate + " bpm");
        }
    }
    
    private void updateSteps() {
        // 模拟步数数据
        int currentSteps = progressSteps != null ? progressSteps.getProgress() : 0;
        int newSteps = Math.min(10000, currentSteps + random.nextInt(500) + 100);
        
        if (tvSteps != null) {
            tvSteps.setText(String.format(Locale.getDefault(), "%,d 步", newSteps));
        }
        
        if (progressSteps != null) {
            progressSteps.setProgress(newSteps);
        }
    }
    
    private void updateSleepData() {
        // 模拟睡眠数据 (6-9小时)
        float sleepHours = 6.0f + random.nextFloat() * 3.0f;
        if (tvSleepTime != null) {
            tvSleepTime.setText(String.format(Locale.getDefault(), "%.1f 小时", sleepHours));
        }
    }
    
    private void setupExerciseTaskSpinner() {
        if (spinnerExerciseTasks != null && getContext() != null) {
            List<String> taskNames = new ArrayList<>();
            taskNames.add("选择杂务任务...");
            
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), 
                    android.R.layout.simple_spinner_item, taskNames);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerExerciseTasks.setAdapter(adapter);
        }
    }
    
    private void updateExerciseTaskSpinner() {
        if (spinnerExerciseTasks != null && getContext() != null) {
            List<String> taskNames = new ArrayList<>();
            taskNames.add("选择杂务任务...");
            
            for (Task task : exerciseTasks) {
                taskNames.add(task.getTitle());
            }
            
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), 
                    android.R.layout.simple_spinner_item, taskNames);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerExerciseTasks.setAdapter(adapter);
        }
    }
    
    private void setupMeditationDurationSpinner() {
        if (spinnerMeditationDuration != null && getContext() != null) {
            String[] durations = {"5分钟", "10分钟", "15分钟", "20分钟", "30分钟"};
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), 
                    android.R.layout.simple_spinner_item, durations);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerMeditationDuration.setAdapter(adapter);
            spinnerMeditationDuration.setSelection(1); // 默认选择10分钟
        }
    }
    
    private void startExercise() {
        if (spinnerExerciseTasks.getSelectedItemPosition() == 0) {
            Toast.makeText(getContext(), "请先选择一个杂务任务", Toast.LENGTH_SHORT).show();
            return;
        }

        isExercising = true;
        exerciseStartTime = System.currentTimeMillis();
        
        // 更新UI
        btnStartExercise.setText("暂停");
        btnCompleteExercise.setEnabled(true);
        spinnerExerciseTasks.setEnabled(false);
        
        // 开始计时器
        exerciseTimer = new CountDownTimer(Long.MAX_VALUE, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                updateExerciseTime();
            }
            
            @Override
            public void onFinish() {
                // 不会被调用，因为我们使用的是最大值
            }
        }.start();
        
        Toast.makeText(getContext(), "开始杂务计时", Toast.LENGTH_SHORT).show();
    }
    
    private void pauseExercise() {
        isExercising = false;
        
        if (exerciseTimer != null) {
            exerciseTimer.cancel();
        }
        
        // 更新UI
        btnStartExercise.setText("继续");
        
        Toast.makeText(getContext(), "杂务已暂停", Toast.LENGTH_SHORT).show();
    }
    
    private void completeExercise() {
        if (exerciseTimer != null) {
            exerciseTimer.cancel();
        }
        
        // 完成选中的任务
        int selectedPosition = spinnerExerciseTasks.getSelectedItemPosition();
        if (selectedPosition > 0 && selectedPosition <= exerciseTasks.size()) {
            Task selectedTask = exerciseTasks.get(selectedPosition - 1);
            selectedTask.setCompleted(true);
            
            // 更新任务到数据库
            if (taskViewModel != null) {
                taskViewModel.updateTask(selectedTask);
                
                // 通知日记系统任务已完成
                com.example.managemyself.util.TaskCompletionNotifier.getInstance().notifyTaskCompleted(selectedTask);
            }
            
            Toast.makeText(getContext(), "杂务任务已完成！", Toast.LENGTH_SHORT).show();
        }
        
        // 重置UI
        resetExerciseUI();
    }
    
    private void resetExerciseUI() {
        isExercising = false;
        exerciseStartTime = 0;
        
        btnStartExercise.setText("开始杂务");
        btnCompleteExercise.setEnabled(false);
        spinnerExerciseTasks.setEnabled(true);
        spinnerExerciseTasks.setSelection(0);
        
        if (tvExerciseTime != null) {
            tvExerciseTime.setText("00:00");
        }
    }
    
    private void updateExerciseTime() {
        if (exerciseStartTime > 0 && tvExerciseTime != null) {
            long elapsedTime = System.currentTimeMillis() - exerciseStartTime;
            int minutes = (int) (elapsedTime / 60000);
            int seconds = (int) ((elapsedTime % 60000) / 1000);
            tvExerciseTime.setText(String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds));
        }
    }
    
    private void startMeditation() {
        int selectedPosition = spinnerMeditationDuration.getSelectedItemPosition();
        int[] durations = {5, 10, 15, 20, 30}; // 分钟
        int durationMinutes = durations[selectedPosition];
        long durationMillis = durationMinutes * 60 * 1000;
        
        isMeditating = true;
        
        // 更新UI
        btnStartMeditation.setEnabled(false);
        btnStopMeditation.setEnabled(true);
        spinnerMeditationDuration.setEnabled(false);
        
        // 开始播放雨声白噪音
        startWhiteNoise();
        
        // 开始倒计时
        meditationTimer = new CountDownTimer(durationMillis, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                updateMeditationTime(millisUntilFinished);
            }
            
            @Override
            public void onFinish() {
                completeMeditation();
            }
        }.start();
        
        Toast.makeText(getContext(), "开始" + durationMinutes + "分钟冥想，正在播放雨声", Toast.LENGTH_SHORT).show();
    }
    
    private void stopMeditation() {
        if (meditationTimer != null) {
            meditationTimer.cancel();
        }
        
        // 停止白噪音
        stopWhiteNoise();
        
        resetMeditationUI();
        Toast.makeText(getContext(), "冥想已停止", Toast.LENGTH_SHORT).show();
    }
    
    private void completeMeditation() {
        // 停止白噪音
        stopWhiteNoise();
        
        resetMeditationUI();
        Toast.makeText(getContext(), "冥想完成！感谢您的坚持", Toast.LENGTH_SHORT).show();
    }
    
    private void resetMeditationUI() {
        isMeditating = false;
        
        btnStartMeditation.setEnabled(true);
        btnStopMeditation.setEnabled(false);
        spinnerMeditationDuration.setEnabled(true);
        
        if (tvMeditationTime != null) {
            tvMeditationTime.setText("00:00");
        }
    }
    
    private void updateMeditationTime(long millisUntilFinished) {
        if (tvMeditationTime != null) {
            int minutes = (int) (millisUntilFinished / 60000);
            int seconds = (int) ((millisUntilFinished % 60000) / 1000);
            tvMeditationTime.setText(String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds));
        }
    }
    
    /**
     * 开始播放白噪音（雨声）
     */
    private void startWhiteNoise() {
        try {
            WhiteNoisePlayer whiteNoisePlayer = WhiteNoisePlayer.getInstance(requireContext());
            whiteNoisePlayer.setPlaybackListener(new WhiteNoisePlayer.PlaybackListener() {
                @Override
                public void onStateChanged(WhiteNoisePlayer.PlayState newState) {
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> {
                            switch (newState) {
                                case PLAYING:
                                    // 可以在这里更新UI显示播放状态
                                    break;
                                case STOPPED:
                                case PAUSED:
                                    // 播放停止或暂停
                                    break;
                            }
                        });
                    }
                }
                
                @Override
                public void onError(String error) {
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "白噪音播放失败: " + error, Toast.LENGTH_SHORT).show();
                        });
                    }
                }
            });
            
            whiteNoisePlayer.setVolume(0.6f); // 设置适中的音量
            whiteNoisePlayer.play();
            
        } catch (Exception e) {
            Log.e(TAG, "启动白噪音失败", e);
            Toast.makeText(getContext(), "白噪音启动失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 停止播放白噪音
     */
    private void stopWhiteNoise() {
        try {
            WhiteNoisePlayer whiteNoisePlayer = WhiteNoisePlayer.getInstance(requireContext());
            whiteNoisePlayer.stop();
        } catch (Exception e) {
            Log.e(TAG, "停止白噪音失败", e);
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        
        // 清理计时器
        if (exerciseTimer != null) {
            exerciseTimer.cancel();
        }
        
        if (meditationTimer != null) {
            meditationTimer.cancel();
        }
        
        // 停止白噪音
        stopWhiteNoise();
    }
} 